<template>
  <el-row class="login-container" type="flex" justify="center" align="middle">
    <el-card width="450px" class="card-header">
      <template #header>
        <div style="text-align: center;">
          <img :src="imgUrl" alt="login-head" />
        </div>
      </template>
      <div class="jump-link">
        <el-link type="primary" @click="handleChanage">{{ formType == 'login' ? '没有账号？去注册' : '返回登录' }}</el-link>
      </div>
      <el-form
      ref="loginFormref"
      :model="loginInfo" label-width="auto" :rules="rules" style="width: 100%; margin-top: 20px;"  >
        <el-form-item label="用户名" prop="userName">
          <el-input v-model="loginInfo.userName" placeholder="请输入用户名/手机号" prefix-icon="User" />
        </el-form-item>
        <el-form-item label="密码" prop="passWord">
          <el-input v-model="loginInfo.passWord" type="password" placeholder="请输入密码" prefix-icon="Lock" />
        </el-form-item>
        <el-form-item label="验证码" prop="validCode" v-if="formType == 'register'">
          <el-input v-model="loginInfo.validCode"  placeholder="请输入验证码" >
            <template #append>
              <button class="valid-button" @click="countdownChange">{{ countdown.validText }}</button>
            </template>
          </el-input>
        </el-form-item>
          <el-form-item>
          <el-button type="primary" style="width: 100%;" @click="handleSubmit(loginFormref)">{{ formType == 'login' ? '登录' : '注册' }}</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </el-row>
</template>

<script setup>
import { ref,reactive ,computed,toRaw} from 'vue'
import { ElMessage } from 'element-plus'
import { getCode, register, login , menuPermission} from '../api/index.js'
import { useRouter } from 'vue-router'
import { useStore } from 'vuex'


const imgUrl = new URL('../../public/login-head.png', import.meta.url).href

const countdown = reactive({
  time: 60,
  disabled: false,
  validText: '获取验证码'
})
var flag = false
const countdownChange = () => {
  if (flag == true) {
    return
  }
  // 手机号验证
  const phoneReg = /^1(3[0-9]|4[01456879]|5[0-35-9]|6[2567]|7[0-8]|8[0-9]|9[0-35-9])\d{8}$/
  if(!loginInfo.userName || !phoneReg.test(loginInfo.userName)){
    console.log(loginInfo.userName)
    return ElMessage({
      message: '请输入正确的手机号',
      type: 'warning',
    })
  }
  
  // 设置按钮为禁用状态
  flag = true
  countdown.disabled = true
  
  // 保存定时器引用，以便后续清除
  const timer = setInterval(() => {
    if (countdown.time <= 0) {
      clearInterval(timer)
      flag = false
      countdown.disabled = false
      countdown.time = 60
      countdown.validText = '获取验证码'
      return
    }
    countdown.time--
    countdown.validText = `重新获取(${countdown.time})`
  }, 1000)

  // 发送请求获取验证码
  getCode({ tel: loginInfo.userName }).then(data => {  
    console.log(data, 'data')
    if(data.code == 10000) {
      ElMessage.success('验证码发送成功')
    } 
  }).catch(err => {
    ElMessage.error('验证码发送失败，请稍后重试')
    })
  .finally(() => {
    // 登录成功后，清除定时器并恢复按钮状态
    clearInterval(timer)
    flag = false
    countdown.disabled = false
    countdown.time = 60
    countdown.validText = '获取验证码'
  })
}


const loginInfo = reactive({
  userName: '',
  passWord: '',
  validCode: ''
})


const formType = ref('login') //login or register
const handleChanage = () => {
  //切换登录和注册
  formType.value == 'login' ? formType.value = 'register' : formType.value = 'login'
  console.log(formType.value)
}

//表单验证规则
const rules = reactive({
  userName: [
    { required: true,
      validator: (rule, value, callback) => {
        if (!value) {
          callback(new Error('请输入用户名/手机号'))
        } else {
          const phoneReg = /^1(3[0-9]|4[01456879]|5[0-35-9]|6[2567]|7[0-8]|8[0-9]|9[0-35-9])\d{8}$/
          phoneReg.test(value) ? callback() : callback(new Error('请输入正确的手机号'))
        }
      },
      trigger: 'blur' 
    },
  ],
  passWord: [
    { required: true,
      validator: (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入密码'))
        } else {
          const reg = /^[a-zA-Z0-9_-]{6,16}$/
          reg.test(value) ? callback() : callback(new Error('密码格式错误，需要6到16位（字母，数字，下划线，减号）'))
        }
      },
      trigger: 'blur'
    },
  ],
  validCode: [
    { required: true,
      message: '请输入验证码',
      trigger: 'blur'
    },
  ]
})
const router = useRouter()
const loginFormref = ref()
const store = useStore()

const routerList = computed(() => {
  return store.state.menu.routerList
})

const handleSubmit = async () => { 
  if (!loginFormref.value) return

  await loginFormref.value.validate((valid) => {
    if (valid) {
      if(formType.value == 'login'){
        //登录逻辑
        login(loginInfo).then(data => { 
          if(data.data.code == 10000) {
            ElMessage.success('登录成功!')
            localStorage.setItem('token',data.data.data.token)
            localStorage.setItem('userInfo',JSON.stringify(data.data.data.userInfo))
            menuPermission().then(data => { 
              store.commit('dynamicMenu',data.data.data)
              console.log(routerList,'routerList')
              toRaw(routerList.value).forEach(item => {
                router.addRoute('main',item)
              });
              router.push('/')
            })  
          } 
        })
      } else {
        //注册逻辑
        register(loginInfo).then(data => {
          console.log(data, 'data')
          if(data.data.code == 10000) {
            ElMessage.success('注册成功!请登录')
            formType.value = 'login'
          } 
        }).catch(err => {
          ElMessage.error('注册失败，请稍后重试')
        })
        // ElMessage.success('注册成功!')
        console.log('注册成功',loginInfo)
      }
    } else {
      console.log('error submit!!', loginInfo)
      console.log(err, 'err')
      return false
    }
  })

}
</script>

<style lang="less" scoped>
:deep(.el-card__header) {
  background-color: #ffffff;
  padding: 0;
}
.login-container {
  height: 100%;
  .card-header{
    background-color: #ffffff;
    img{
      width: 430px;
    }
  }
  .jump-link{
    text-align: right;
    margin-top: 10px;
  }
}

.valid-button{
  border: none;
  background: none;
  color: #409EFF;
  cursor: pointer;
}
</style>
